package com.net.io.netty.stickhalfpk.resolve.linebase;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author zhangtengfei
 * @date 2022/2/15 14:42
 */
public class LineBaseClientHandler extends SimpleChannelInboundHandler<ByteBuf> {

    private AtomicInteger counter = new AtomicInteger(0);

    /**
     * 客户端读取到网络数据后的处理
     */
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
        System.out.println("client Accept[" + msg.toString(CharsetUtil.UTF_8) + "] and the counter is:" + counter.incrementAndGet());
        ctx.close();
    }

    /**
     * 客户端被通知channel活跃后，做事
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        ByteBuf msgByteBuf;
        System.out.println(System.getProperty("line.separator"));// 换行符\r\n
        String request = "Mark,Lison,King,James,Deer" + System.getProperty("line.separator"); // Mark,Lison,King,James,Deer\r\n
        for (int i = 0; i < 100; i++) {
            msgByteBuf = Unpooled.buffer(request.length());
            msgByteBuf.writeBytes(request.getBytes());
            ctx.writeAndFlush(msgByteBuf);
        }
    }

    /**
     * 发生异常后的处理
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
